package battleship;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class LoginInfo {
	public static boolean loggedIn(HttpSession session) {
		return session != null
				&& session.getAttribute(Constants.ATTR_UID) != null;
	}

	public static String getLinks(HttpServletRequest request) throws SQLException {
		Object uid = null;
		String contents = "";
		
		final HttpSession session = request.getSession(false);
		if (session != null) {
			uid = session.getAttribute(Constants.ATTR_UID);
		}
		
		final Connection con =  Database.open();
		PreparedStatement ps = con
		.prepareStatement("select * from User where uid=?");
		ps.setString(1, (String) uid);
		final ResultSet rs = ps.executeQuery();
		String avatarid = "";
		if (rs.next()) 
		{
			avatarid = rs.getString("avatar");
		}
		

		if (uid == null) {
			contents = "<a href=\"/login.jsp\">Log in</a>";
		} else {
			contents = "<a href=\"index.jsp\">Main</a> | "
					+ String.format("Logged in as <b>%s</b>", uid.toString())
					+ " | <a href=\"logout.jsp\">Log out</a>"+
					"<br><img src='avatar"+avatarid+".png'></img>";
			
		}

		return "<div id=\"userlinks\">" + contents + "</div>";
	}
}
